from rest_framework.views import APIView
from apps.inform.models import Inform,InformRead
from apps.inform.serializers import InformSerializer
from django.db.models import Q
from django.db.models import Prefetch
from apps.absent.models import Absent
from apps.absent.serializers import AbsentSerializer
from apps.oaauth.models import OAAbstractUser,OADepartment
from apps.oaauth.serializers import UserSerializer,DeptSerializer
from django.db.models import Count
from rest_framework.response import Response
from django.views.decorators.cache import cache_page
from django.utils.decorators import method_decorator
from rest_framework.permissions import AllowAny


#返回最新的十条通知
class LatestInformView(APIView):
    @method_decorator(cache_page(60*15))   #  缓存15分钟
    def get(self,request):
        #返回公共的或者我所在部门的通知
        informs = Inform.objects.prefetch_related(
            Prefetch("reads", queryset=InformRead.objects.filter(user=self.request.user))).filter(
            Q(public=True)|Q(department=self.request.user.department)|Q(author=self.request.user))[:10]
        serializer = InformSerializer(informs,many=True)
        return Response(serializer.data)

class LatestAbsentView(APIView):
    # @method_decorator(cache_page(60 * 10))  # 缓存10分钟
    def get(self,request):
        user = request.user
        if user.department.name == '董事会':
            absents = Absent.objects.all().order_by('-creat_time')[:10]
        else:
            absents = Absent.objects.filter(requester__department_id=user.department_id).order_by('-creat_time')[:10]
        serializer = AbsentSerializer(absents,many=True)
        data = serializer.data
        return Response(data)


class StaffCountView(APIView):
    @method_decorator(cache_page(60 * 15))  # 缓存15分钟
    def get(self,request):
        dept = OADepartment.objects.annotate(count=Count('staff')).values('name','count')
        print('='*10)
        return Response(dept)

class HealthCheckView(APIView):
    permission_classes = [AllowAny]
    def get(self,request):
        return Response({'code':'ok'})